﻿using Kinlo.Entitys;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using UIWindows.GlobalStatics;
using UIWindows.Services.Context;
using UIWindows.Tools.Helper;
using XingLucifer.Devices;
using XingLucifer.IBase.Enums;

namespace UIWindows.Services.Handle
{
    [Attributes.TaskClass(TaskTypes.补液量发送)]
    public class LiquidFillingPump : ServierBase
    {
        Dictionary<string, int> _keyValues;
        public LiquidFillingPump(DeviceConfigStatic deviceConfig, SystemConfigStatic systemConfig,
            UserConfigStatic userConfig, ParameterStatic parameterStatic, TemporaryStatic temporaryStatic, HomeStatic homeStatic, MesParameterStatic mesParameterStatic)
            : base(deviceConfig, systemConfig, userConfig, parameterStatic, temporaryStatic, homeStatic, mesParameterStatic)
        {
            _keyValues = new Dictionary<string, int>() {
                { "PC_RehydrationVolumeUP[0]", 3500 },
                { "0", 3500 },
                { "1", 3500 },
                { "2", 3500 },
                { "3", 3500 },
                { "4", 3500 },
                { "5", 3500 },
                //=============//
                { "6", 3520 },
                { "7", 3520 },
                { "8", 3520 },
                { "9", 3520 },
                { "10", 3520 },
                { "11", 3520 },
            };
        }

        public override Task Handle(DataContext context)
        {
            if (!ClearSignal(context)) { return Task.CompletedTask; }
            try
            {
                var plc = _deviceConfig.DeviceList.FirstOrDefault(x => x.ServiceName == context.ServiceName && x.TaskType == TaskTypes.扫描信号).Communication as OmronCIP;
                DateTime weighing_time = DateTime.Now;
                var erinnerungen = ReadOneErinnerungen(plc, context.Address_Struct, context.Struct_Length, _systemConfig.IAddress.Erinnerungen_RehydrationVolume, context.AddressingMethod);
                if (erinnerungen.Item1)
                {
                    $"==>>{context.TaskType}<<==\r\n收到启动信号，没收到电池记忆，请联系电气工程师！！！".MessageDialogs(MessageLevelType.错误, false, Enums.PopUpTypes.Global);
                    return base.Handle(context);
                }
                RunLog($"记忆ID：{erinnerungen.Item2.SnowflakeId}");
                Models.Devices.DeviceClientModel? device = _deviceConfig.DeviceList.FirstOrDefault(x => x.ServiceName == context.ServiceName && x.TaskType == context.TaskType
                                && x.DeviceType == context.DeviceType && x.Index == context.DeviceIndex);
                var battery = erinnerungen.Item2;
                if (battery.SnowflakeId == -1)
                {
                    RunLog($"-[{battery.Index}] 点检注液量：{battery.Data_PLC} g");
                    bool bl1 = false;
                    if (device == null)
                    {
                        RunLog($"找不到[{context.DeviceIndex}]号设备", MessageLevelType.错误);
                        bl1 = true;
                    }
                    else
                    {
                        bl1 = SendInj(battery.Data_PLC, _keyValues[context.Address_Struct], device);
                    }
                    WriteResult("", bl1 ? ResultTypes.合格 : ResultTypes.不合格, plc, battery.Address_Struct, context);
                    return base.Handle(context);
                }
                DateTime dateTime = DateTime.Now;
                ProductionData? entity = _temporaryStatic.EntityCache.FirstOrDefault(x => x.SnowflakeId == battery.SnowflakeId);
                if (entity == null)
                {
                    RunLog($"-[{battery.Index}] 实体缓存查询不到==>[{battery.SnowflakeId}]，转到数据库查询");
                    entity = dateTime.GetEntity(context.TaskType, battery.SnowflakeId);
                }
                else
                {
                    ProductionData.Meta.TableName = entity.Items["TableName"].ToString();
                }
                if (entity == null)
                {
                    RunLog($"-[{battery.Index}] 数据库找不到ID为：{battery.SnowflakeId}");
                    WriteResult("", ResultTypes.数据库找不到电池, plc, battery.Address_Struct, context);
                    return base.Handle(context);
                }
                bool? bl = null;
                if (battery.Data_PLC > ((float)Math.Abs(entity.TotalInjectionVolumeDeviationValue)) - 0.1 && (battery.Data_PLC < ((float)Math.Abs(entity.TotalInjectionVolumeDeviationValue)) + 0.1))
                {
                    if (device == null)
                    {
                        bl = true;
                        RunLog($"-[{context.Address_Struct}] 找不到[{battery.Index}]#注液泵设备");
                    }
                    else
                    {
                        bl = SendInj(battery.Data_PLC, _keyValues[context.Address_Struct], device);
                    }
                    RunLog($"-[{battery.Index}] ID：[{battery.SnowflakeId}] 条码：[{entity.BarCode}] 注液量发送结果：{(bl == true ? "成功" : "失败")}");
                }
                else
                {
                    RunLog($"-[{battery.Index}] ID：[{battery.SnowflakeId}] 条码：[{entity.BarCode}] 注液量对比失败 记忆注液量：[{battery.Data_PLC}] 电池注液量：[{(float)Math.Abs(entity.TotalInjectionVolumeDeviationValue)}]");
                }
                entity.ResultInjSend = bl == null ? ResultTypes.注液量不匹配 : (bl == true ? ResultTypes.合格 : ResultTypes.注液量发送失败);

                try
                {
                    entity.Update();
                }
                catch (Exception ex)
                {
                    RunLog($"-[{battery.Index}] ID：[{battery.SnowflakeId}] 条码：[{entity.BarCode}] 数据更新异常：{ex}");
                }
                WriteResult(entity.BarCode, entity.ResultInjSend, plc, battery.Address_Struct, context);
            }
            catch (Exception ex)
            {
                RunLog($"异常：{ex}");
            }
            return base.Handle(context);
        }


    }
}
